package com.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mh.entity.LoginUser;
import com.mh.entity.SysUser;
import com.mh.mapper.SysMenuMapper;
import com.mh.mapper.SysRoleMapper;
import com.mh.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysMenuMapper menuMapper;
    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息
        //创建QueryWrapper对象,设置WHERE条件
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username); //"user_name"需要与数据库字段名一致
        //SQL的WHERE条件传入
        SysUser users = userMapper.selectOne(wrapper);

        //如果查询结果是空,则抛出异常
        if (users == null) {
            throw new UsernameNotFoundException(username);
        }

        //查询用户权限们,封装到集合中
        //ArrayList<String> permissions = new ArrayList<>(Arrays.asList("test"));
        //selectPermsByUserId形参需要传入userId,从上面获取到的SysUser对象中获取
        List<String> perms = menuMapper.selectPermsByUserId(users.getUserId());

        //查询用户角色们,封装到集合中
        List<String> roles = roleMapper.selectRolesByUserId(users.getUserId());

        //查询结果非空,则调用LoginUser(自定义UserDetails的实现类)有参构造,传入SysUser对象
        return new LoginUser(users,perms,roles);
    }
}
